package com.ziytek.web.citizen.listener;

import com.google.gson.Gson;
import com.ziytek.web.citizen.event.RealDataEvent;
import com.ziytek.web.citizen.service.JobService;
import com.ziytek.web.citizen.service.PushDataService;
import com.ziytek.web.citizen.service.RealDataProService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/***
 * 电池实时数据事件监听
 * @author fenghx
 * */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RealDataEventListener {

    private final Gson gson;
    private final JobService jobService;
    private final PushDataService pushDataService;
    private final RealDataProService realDataProService;

    @Async("myAsyncExecutor")
    @EventListener
    public void realDataEventListener(RealDataEvent event) {
        Assert.notNull(event, "RealDataEvent can not be null");
        Assert.notNull(event.getRealData(), "RealDataEvent RealData can not be null");

        try {
            // 周期数据处理
            realDataProService.process(event.getRealData());
            // 如果是指令下发上送的第一帧数据，开启指令缓存及容量数据统计定时任务
            jobService.jobStart(event.getRealData());
            // 给web前端推送长连接数据
            pushDataService.pushData(event.getRealData());

            log.info("周期数据处理成功,cab:{}", event.getRealData().getB());
        } catch (Exception e) {
            log.info("周期数据处理失败,cab:{}-{}", event.getRealData().getB(), gson.toJson(event));
        }
    }
}
